import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { Observable, Observer } from 'rxjs';
import getData_ajax from '../../common/utils/getData_ajax';
import config from '../../common/utils/baseUrl';
import * as $ from 'jquery';
import { NzModalService } from 'ng-zorro-antd';
import { HttpClient } from '@angular/common/http';
import promise from '../../common/utils/promise';
import { Router } from '@angular/router';

@Component({
  selector: 'app-personal-information',
  templateUrl: './personal-information.component.html',
  styleUrls: ['./personal-information.component.scss'],
})
export class PersonalInformationComponent implements OnInit {
  validateForm: FormGroup;

  // 加载状态
  public isSpinning: any = false;
  // 资料数据
  public informationData: any = [];
  // 表单是否处于只读
  public isReadOnly: any = true;
  // 上传的图片数据
  public sendImgdata: any = {};

  constructor(private fb: FormBuilder, private modal: NzModalService,
              private http: HttpClient, private router: Router) {
    this.validateForm = this.fb.group({
      show_img: [''],
      name: ['', [Validators.required]],
      position: ['', [Validators.required]],
      personalProfile: ['', [Validators.required]],
    });
  }

  ngOnInit() {
    this.getData();
  }

  /**
   * 拉去数据
   */
  getData() {
    let that = this;
    that.isSpinning = true;
    promise.commonRequest.post('', '/api/informationService/getInformationData').then(data => {
      // @ts-ignore
      if (data.isEffective) {
        // @ts-ignore
        this.isSpinning = false;
        // @ts-ignore
        this.informationData = data.result[0];
        // 渲染表单
        this.validateForm.patchValue({
          name: that.informationData.name,
          position: that.informationData.position,
          personalProfile: that.informationData.personalProfile,
        });
      } else {
        this.router.navigateByUrl('/passport/login');
        sessionStorage.setItem('previousUrl', window.location.pathname);
      }
    }).catch(error => {
      if (!error.responseJSON.isEffective) {
        this.router.navigateByUrl('/passport/login');
        sessionStorage.setItem('previousUrl', window.location.pathname);
      }
    });
  }

  /**
   * 更换头像
   */
  changeImgFunc() {
    return $('#show_img').click();
  }

  imgChange() {
    // //传标题图片到后台处理
    let titleImg = $('#show_img')[0]; //因为得到的是一个jquery类型，所以需要转化为js类型
    let titleImgFile = titleImg.files;  //获取上一步获取的titlefile对象里面的files属性名
    for (let i = 0; i < titleImgFile.length; i++) {
      this.sendImg(titleImgFile[i]);  //执行上面的titleImgFile
    }
  }

  sendImg(file) {
    let that = this;
    this.sendImgdata = new FormData();  //动态创建form表单的一个ectype属性
    this.sendImgdata.append('myfile', file);
    getData_ajax.uploadImg(config.uploadImgUrl + '/api/inputService/uploadImg', that.sendImgdata, function(data) {
        that.informationData.headerImg = data.data[0];
      },
      function(error) {
        console.log(error);
      });
  }

  /**
   * 重置表单
   * @param e
   */
  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  /**
   * 修改表单
   */
  editFormFunc() {
    this.isReadOnly = false;
  }

  /**
   * 提交表单
   * @param $event
   * @param value
   */
  submitForm = ($event, value) => {
    var that = this;
    $event.preventDefault();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
      if (this.validateForm.controls[key].errors != null) {
        return;
      }
    }
    this.validateForm.value.headerImg = this.informationData.headerImg;
    // 请求接口
    this.modal.confirm({
      nzTitle: '确定？',
      nzContent: '<b>确定修改个人信息</b>',
      nzOnOk: () =>
        promise.commonRequest.post(this.validateForm.value, '/api/informationService/editInformation').then(data => {
          // @ts-ignore
          if (data.isEffective) {
            this.modal.success({
              nzTitle: '成功！',
              nzContent: '成功修改个人信息！',
            });
            this.isReadOnly = true;
            this.getData();
          } else {
            this.router.navigateByUrl('/passport/login');
            sessionStorage.setItem('previousUrl', window.location.pathname);
          }
        }).catch(error => {
          if (!error.responseJSON.isEffective) {
            this.router.navigateByUrl('/passport/login');
            sessionStorage.setItem('previousUrl', window.location.pathname);
          } else {
            this.modal.error({
              nzTitle: '失败！',
              nzContent: '错误，请稍后再试....',
            });
          }
        }),
    });
  };
}
